<template>
  <div>
    <el-input class="input" placeholder="请输入内容" prefix-icon="el-icon-search" v-model="likeName" @keydown.enter.native="search">
    </el-input>
    <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
    <el-button type="primary" @click="dialog=true">新增</el-button>
    <el-table :data="userData" style="width: 100%;">
      <el-table-column prop="account" label="账号"> </el-table-column>
      <el-table-column prop="name" label="姓名">
        <template slot-scope="scope">{{scope.row.name}}</template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time|formatDate}}</template>
      </el-table-column>
      <el-table-column prop="sex" label="性别">
        <template slot-scope="scope">
          <el-tag type="danger">{{sexName[scope.row.sex]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="送货地址"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="changeUpdateDrawer(scope.row)">编辑</el-button>
          <el-button type="text" @click="delUser(scope.row.user_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- @size-change 自定义事件 page-sizes 总页数的集合 page-size 总页数-->
    <el-pagination @size-change="changeMaxSize" @current-change="changePageSize" :current-page="currentPage"
      :page-sizes="pageSizes" :page-size="pageSize" layout="total,sizes,prev,pager,next,jumper" :total="total">
    </el-pagination>
    <!-- 打开抽屉-->
    <el-drawer title="新增用户" :before-close="cancel" :visible.sync="dialog" direction="ltr" custom-class="demo-drawer"
      ref="addDrawer" size="50%">
      <!-- 表单组件 -->
      <div class="form-contaniner">
        <el-form label-position="left" :model="user" :rules="rules" ref="addUser">
          <el-form-item label="账号" prop="account">
            <el-input v-model="user.account"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="user.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="user.name"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="user.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio v-model="user.sex" label="0">保密</el-radio>
            <el-radio v-model="user.sex" label="1">男</el-radio>
            <el-radio v-model="user.sex" label="2">女</el-radio>
          </el-form-item>
          <el-form-item label="收货地址" prop="address">
            <el-input v-model="user.address"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button>取消</el-button>
            <el-button type="primary" @click="addUser('addUser')">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <!--修改抽屉-->
    <el-drawer title="修改用户" :before-close="cancel" :visible.sync="updateDialog" direction="rtl" custom-class="demo-drawer"
      ref="updateDrawer" size="50%">
      <!--表单组件-->
      <div class="form-contaniner">
        <el-form label-position="left" :model="user" :rules="rules" ref="updateUser">
          <el-form-item label="账号" prop="account">
            <el-input v-model.lazy="user.account"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model.lazy="user.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model.lazy="user.name"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.lazy="user.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model.lazy="user.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model.lazy="user.sex">
              <el-radio :label="0">保密</el-radio>
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item prop="address">
          <el-form-item label="收货地址">
            <el-input v-model="user.address"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button>取消</el-button>
            <el-button type="primary" @click="updateUser('updateUser')">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <el-button type="primary" @click="routerChange(1)">
      布局
    </el-button>
    <el-button type="primary" @click="routerChange(2)">
      布局容器
    </el-button>
  </div>
</template>

<script>
  import axios from 'axios'
  import qs from 'qs'
  export default {
    data() {
      return {
        userData: [],
        currentPage: 1,
        pageSizes: [10, 100, 200, 500, 1000],
        pageSize: 10,
        total: 400,
        sexName: ["保密", "男", "女"],
        likeName: null,
        dialog: false,
        user: {
          account: "",
          password: "",
          name: "",
          email: "",
          phone: "",
          sex: 0,
          address: ""
        },
        rules: {
          account: [{
            required: true,
            message: "用户的账号不能为空",
            trigger: "blur"
          }],
          password: [{
            required: true,
            message: "用户的密码不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "用户的姓名不能为空",
            trigger: "blur"
          }],
          email: [{
            type: "email",
            message: "用户的邮箱格式不正确",
            trigger: "change"
          }, {
            required: true,
            message: "用户的邮箱不能为空",
            trigger: "blur"
          }],
          phone: [{
            required: true,
            message: "用户的手机号不能为空",
            trigger: "blur"
          }],
          address: [{
            required: true,
            message: "用户的收货地址不能为空",
            trigger: "blur"
          }],
        },
        updateDialog: false
      }
    },
    components: {

    },
    methods: {
      routerChange(index) {
        if (index == 1) {
          this.$router.push("/element1");
        }else if(index==2){
          this.$router.push('/element2')
        }
      },
      //改变一页容纳的总条数
      changeMaxSize(maxSize) {
        /* console.log(maxSize) */
        //默认接收到总条数，但是我需要总条数和当前页码
        let currentPage = this.currentPage
        let likeName = this.likeName
        this.getUserData(currentPage, maxSize, likeName)

      },
      //改变页码时
      //默认接收的是改变的页码，但是我需要总条数和当前页码
      changePageSize(currentPage) {
        /* console.log(pageSize) */
        let maxSize = this.pageSize
        let likeName = this.likeName
        this.getUserData(currentPage, maxSize, likeName)
      },
      getUserData(page, maxSize, likeName) {
        let params = {
          page,
          maxSize
        }
        if (likeName !== "" && likeName !== null) {
          params['likeName'] = likeName
        }

        axios.get("http://chenxueli.site:8081/ssm/selectPageUserList", {
            params
          })
          .then((res) => {
            console.log(res)
            if (res.data.resultCode == 0) {
              //将获取到的真实数据赋给变量
              let data = res.data.data
              //将列表数据复制到data的userData属性中
              this.userData = data.list
              //当前页面
              this.currentPage = data.pageNum
              //一页显示的总条数
              this.pageSize = data.pageSize
              //总条数
              this.total = data.total
            } else {
              alert(res.data.message)
            }
          })
      },
      search() {
        /* let likeName = this.likeName
        let maxSize = 10
        let page = this.page
        this.getUserData(page, maxSize, likeName) */
        let likeName = this.likeName
        let pageSize = this.pageSize
        this.getUserData(1, pageSize, likeName)
      },
      delUser(userId) {

        let params = {
          userId
        }

        this.$confirm("此操作将永久删除该记录", "是否继续", {
          confirmButtonText: "残忍丢弃",
          cancelButtonText: "容我再想想",
          type: "warning"
        }).then(() => {
          //点击确认

          params = qs.stringify(params);
          axios.post("http://chenxueli.site:8081/ssm/deleteUser", params).then((res) => {
            console.log(res)
            if (res.data.resultCode == 0) {
              this.$message({
                type: "success",
                message: res.data.message
              })
              let page = this.currentPage
              let maxSize = this.pageSize
              let likeName = this.likeName
              this.getUserData(page, maxSize, likeName)
            } else {
              this.$message({
                type: "error",
                message: res.data.message
              })
            }
          })

        }).catch(() => {
          //点击取消

        });

      },
      //关闭抽屉
      cancel(done) {
        done();
      },
      //关闭抽屉
      cancel(done) {
        //先将表格的数据清除
        this.user = {
          account: "",
          password: "",
          name: "",
          email: "",
          phone: "",
          sex: 0,
          address: ""
        }
        done();
      },
      //添加用户
      addUser(refName) {
        //校验
        this.$refs[refName].validate((valid) => {
          if (valid) {
            //校验成功，发送请求给服务器进行新增
            let params = this.user;
            params = qs.stringify(params);
            axios.post("http://chenxueli.site:8081/ssm/addUser", params).then((res) => {
              if (res.data.resultCode === 0) {
                this.$message({
                  //给出新增成功的提示
                  type: "success",
                  message: res.data.message
                })
                //抽屉内的内容全部清空
                this.$refs[refName].resetFields()
                //关闭抽屉

                this.dialog = false
                //获取第一页的数据
                this.getUserData(1, 10, null)
              } else {
                //给出修改失败的提示
                this.$message({
                  type: "error",
                  message: res.data.message
                })
              }
            })
          } else {
            return false;
          }
        })
      },
      //切换修改抽屉，将数据回显到抽屉中
      changeUpdateDrawer(user) {
        //将获取到的旧数据复制给data中
        this.user = user
        //打开修改抽屉
        this.updateDialog = true
      },
      //修改用户
      updateUser(refName) {
        this.$refs[refName].validate((valid) => {
          if (valid) {
            let user = this.user;
            const param = (({
              user_id,
              account,
              password,
              name,
              head_img_url,
              address,
              email,
              phone,
              sex,
              version
            }) => ({
              user_id,
              account,
              password,
              name,
              head_img_url,
              address,
              email,
              phone,
              sex,
              version
            }))(user)
            let params = qs.stringify(param);
            axios.post("http://chenxueli.site:8081/ssm/updateUser", params).then((res) => {
              if (res.data.resultCode === 0) {
                //给出修改成功的提示
                this.$message({
                  type: "success",
                  message: res.data.message
                })
                //抽屉内的内容全部清空
                this.$refs[refName].resetFields()
                //关闭抽屉
                this.updateDialog = false
                //获取当前页的数据

                this.getUserData(this.currentPage, this.pageSize, this.likeName)
              } else {
                //修改失败的提示
                this.$message({
                  type: "error",
                  message: res.data.message
                })
              }
            })
          } else {
            return false
          }
        })
      }
    },
    mounted() {
      /* 第几页(pageSize)，一页几条(maxSize) */
      this.getUserData(1, 10, null)
    },
    //过滤器
    filters: {
      formatDate(date) {
        return new Date(date).toLocaleString().replace(/:\d{1,2}$/, ' ');
      }
    }
  }
</script>

<!--  <style scoped="scoped"> -->
<style scoped="scoped">
  .input {
    width: 180px;
  }

  .form-contaniner {
    width: 100%;
    height: 600px;
    overflow-y: scroll;
  }

  /* .demo-drawer{
    background-color: deeppink;
  } */
</style>
